BEGIN;
	DROP TRIGGER IF EXISTS trigger_mark_offers_when_accepterd ON offers;
	DROP TRIGGER IF EXISTS trigger_mark_offers_when_accepted ON offers;
	DROP FUNCTION IF EXISTS mark_offers_when_accepterd();
	DROP FUNCTION IF EXISTS mark_offers_when_accepted();

	CREATE FUNCTION mark_offers_when_accepted() RETURNS trigger AS $$
	BEGIN
		IF 'UPDATE'=TG_OP THEN
			IF NOT(OLD.item_owner_agreed AND OLD.requester_agreed) AND NEW.item_owner_agreed AND NEW.requester_agreed THEN
				UPDATE offers SET another_offer_accepted=true WHERE request_id=NEW.request_id AND id!=NEW.id;
			END IF;
		ELSIF 'INSERT'=TG_OP THEN
			IF NEW.item_owner_agreed AND NEW.requester_agreed THEN
				UPDATE offers SET another_offer_accepted=true WHERE request_id=NEW.request_id AND id!=NEW.id;
			END IF;
		END IF;
		RETURN NEW;
	END;
	$$ LANGUAGE plpgsql;

	CREATE TRIGGER trigger_mark_offers_when_accepted AFTER INSERT OR UPDATE ON offers FOR EACH ROW EXECUTE PROCEDURE mark_offers_when_accepted();
END;
